/** 创建一个和DOM元素相同尺寸的占位符，一般用于fixed层例如导航
 * 使用方法：v-placeholder="value"
 * value: false和0(不占位) | 其它(占位)
 */
import { onwidth } from "../__use/resize";

function size(el) {
  if (!el.__placeholder) return;
  // 窗口从pc切换成手机时，watcher并监测不到el变小
  // 此时placeholder本来就是原本pc那么大，所以fixed的el也还是原来pc那么大
  // 这里先把placeholder的宽高清除再重新计算el的宽高
  el.__placeholder.e.style.width = '';
  el.__placeholder.e.style.height = '';
  let box = el.getBoundingClientRect();
  el.__placeholder.e.style.width = box.width + "px";
  el.__placeholder.e.style.height = box.height + "px";
}

function show(el, binding, vnode, prevVnode) {
  const value = binding.value != false;
  if (value) {
    // 已经展示了不需要重新展示
    if (!el.__placeholder) {
      // 仅在组件根元素前插入占位div，如果外层布局为flex可能会有问题
      let e = document.createElement("div");
      el.parentElement.insertBefore(e, el);

      const watcher = new ResizeObserver(() => requestAnimationFrame(() => size(el)))
      watcher.observe(el);

      el.__placeholder = { e, watcher, resize: () => size(el) };
      size(el);

      // 窗口从pc切换成手机时，watcher并监测不到el变小
      onwidth(el.__placeholder.resize, false);
    }
  } else {
    if (el.__placeholder) {
      onwidth(el.__placeholder.resize, true);
      el.__placeholder.watcher.unobserve(el);
      el.__placeholder.watcher.disconnect();
      if (el.__placeholder.e.parentElement) {
        el.__placeholder.e.parentElement.removeChild(el.__placeholder.e);
      }
      delete el.__placeholder;
    }
  }
}

export default {
  mounted: show,
  updated: show,
  unmounted(el) { show(el, { value: 0 }) }
}